package server

import (
	"encoding/json"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"server/src/global"
	"server/src/model"
	"server/src/utils"
	"strconv"
	"time"
)

type robotUser struct {
}

// 更新群信息
func (r *robotUser) UpdateRobotGroupInfo(groupInfo *model.WeChatGroup) (*model.WeChatGroup, error) {
	err := global.GVL_DB.Model(&model.WeChatGroup{}).
		Where("login_token = ?", groupInfo.LoginToken).Updates(groupInfo).Error
	global.GVL_DB.Where("login_token = ?", groupInfo.LoginToken).First(groupInfo)
	fmt.Println("群信息:", groupInfo)
	return groupInfo, err
}

// 更新群用户信息
func (r *robotUser) UpdateRobotGroupUserInfo(groupUserInfo *model.WeChatGroupUser) (*model.WeChatGroupUser, error) {
	err := global.GVL_DB.Where("gid = ? AND wx_user_id = ? AND name = ?",
		groupUserInfo.Gid, groupUserInfo.WxUserId, groupUserInfo.Name).First(&groupUserInfo).Error
	if err != nil {
		rowsAffected := global.GVL_DB.Where("gid = ? AND( wx_user_id = ? OR name = ?)",
			groupUserInfo.Gid, groupUserInfo.WxUserId, groupUserInfo.Name).Updates(groupUserInfo).RowsAffected
		if rowsAffected != 1 {
			fmt.Println("创建用户")
			err := global.GVL_DB.Create(groupUserInfo).Error
			if err != nil {
				return nil, err
			}
		}
	}
	global.GVL_DB.Where("gid = ? AND wx_user_id = ? OR name = ?",
		groupUserInfo.Gid, groupUserInfo.WxUserId, groupUserInfo.Name).First(groupUserInfo)
	return groupUserInfo, nil
}

// 在数据库中验证机器人logintoken
func (r *robotUser) VerifyLoginToken(LoginToken string) (*model.WeChatGroup, error) {
	resInfo := &model.WeChatGroup{}
	db := global.GVL_DB.Model(&model.WeChatGroup{})
	var count int64
	count = 0
	db.Where("login_token = ?", LoginToken).Count(&count).Find(&resInfo)
	if count == 1 {
		return resInfo, nil
	} else {
		return resInfo, errors.New("token not found")
	}
}

// 设置用户信息到redis
func (p *robotUser) SetUserToRedis(adminuser *model.WeChatGroup) (string, error) {
	// 生成唯一标识符
	uuid := utils.GetUuid(strconv.Itoa(adminuser.Id) + adminuser.WeChatGroupName)

	// 将用户信息转换为 JSON 格式
	userJSON, err := json.Marshal(adminuser)
	if err != nil {
		return "", err
	}

	// 设置键值对到 Redis
	r := global.GVL_REDIS
	// 检查 Redis 中是否存在该用户信息
	exists, err := r.Conn.Exists(r.Ctx, uuid).Result()
	if err != nil {
		return "", err
	}

	// 如果 Redis 中存在该用户信息，则更新
	if exists > 0 {
		err := r.Conn.Set(r.Ctx, uuid, string(userJSON), time.Duration(6)*time.Hour).Err()
		if err != nil {
			return "", err
		}
	} else {
		// 如果 Redis 中不存在该用户信息，则直接存入
		err := r.Conn.Set(r.Ctx, uuid, string(userJSON), time.Duration(6)*time.Hour).Err()
		if err != nil {
			return "", err
		}
	}

	return uuid, nil
}

// 从redis中获取用户信息
func (p *robotUser) GetUserToRedis(token string) (*model.WeChatGroup, error) {
	userJSON, err := global.GVL_REDIS.Conn.Get(global.GVL_REDIS.Ctx, token).Result()
	if err != nil {
		return nil, err
	}
	// 解析用户信息 JSON
	user := &model.WeChatGroup{}
	if err := json.Unmarshal([]byte(userJSON), user); err != nil {
		// 如果解析出错，返回错误信息
		return nil, err
	}
	return user, nil
}

// 更新群用户积分信息
func (r *robotUser) UpdateIntegral(groupUserInfo *model.DivisionRecord, Bool bool) (int, string, float64, bool, error) {
	// 开启一个新的事务
	tx := global.GVL_DB.Begin()
	var err error
	var name string
	var score float64
	var BBool bool
	UpAndDown := 0
	NewWeChatGroupUser := &model.WeChatGroupUser{}
	err = tx.Model(&model.WeChatGroupUser{}).Where("id = ?", groupUserInfo.UserID).Find(&NewWeChatGroupUser).Error
	name = NewWeChatGroupUser.Name
	if Bool {
		BBool = true
		//判断上分还是下分
		if groupUserInfo.Division > 0 {
			//上分
			UpAndDown = 1
			score = groupUserInfo.Division
			err = tx.Model(&model.WeChatGroup{}).Where("id = ?", groupUserInfo.Gid).Updates(map[string]interface{}{
				"upward_division": gorm.Expr("upward_division + ?", groupUserInfo.Division),
			}).Error
			if err != nil {
				tx.Rollback()
				return UpAndDown, name, score, BBool, err
			}
			err = tx.Model(&model.WeChatGroupUser{}).Where("id = ?", groupUserInfo.UserID).Updates(map[string]interface{}{
				"upward_division": gorm.Expr("upward_division + ?", groupUserInfo.Division),
				"sum_score":       gorm.Expr("sum_score + ?", groupUserInfo.Division),
			}).Error
			if err != nil {
				tx.Rollback()
				return UpAndDown, name, score, BBool, err
			}
		} else {
			//  下分  执行更新操作
			UpAndDown = -1
			score = -groupUserInfo.Division
			err = tx.Model(&model.WeChatGroup{}).Where("id = ?", groupUserInfo.Gid).Updates(map[string]interface{}{
				"lower_division": gorm.Expr("lower_division - ?", groupUserInfo.Division),
			}).Error
			err = tx.Model(&model.WeChatGroupUser{}).Where("id = ?", groupUserInfo.UserID).Updates(map[string]interface{}{
				"lower_division": gorm.Expr("lower_division - ?", groupUserInfo.Division),
			}).Error
		}
		// 执行创建积分变动记录的操作
		groupUserInfo.Status = 3
		err = tx.Model(&model.DivisionRecord{}).Where("id = ?", groupUserInfo.Id).Updates(&groupUserInfo).Error
		// 检查是否有错误发生
		if err != nil {
			// 如果有错误，回滚事务
			tx.Rollback()
			return UpAndDown, name, score, BBool, err
		} else {
			// 如果所有操作都成功，提交事务
			tx.Commit()
			return UpAndDown, name, score, BBool, nil
		}
	} else {
		BBool = false
		if groupUserInfo.Division < 0 {
			//下分被拒绝
			score = -groupUserInfo.Division
			err = tx.Model(&model.WeChatGroupUser{}).Where("id = ?", groupUserInfo.UserID).Updates(map[string]interface{}{
				"sum_score": gorm.Expr("sum_score - ?", groupUserInfo.Division),
			}).Error
		}
		// 执行创建积分变动记录的操作
		groupUserInfo.Status = 1
		err := tx.Model(&model.DivisionRecord{}).Where("id = ?", groupUserInfo.Id).Updates(&groupUserInfo).Error
		if err != nil {
			// 如果有错误，回滚事务
			tx.Rollback()
			return UpAndDown, name, score, BBool, err
		} else {
			// 如果所有操作都成功，提交事务
			tx.Commit()
			return UpAndDown, name, score, BBool, nil
		}
	}
}

// 更新用户是否发送给系统的信息
func (r *robotUser) UpDataSendSystem(groupUserInfo *model.DivisionRecord, Bool bool) error {
	// 开启一个新的事务
	tx := global.GVL_DB.Begin()

	if Bool {
		// 执行创建积分变动记录的操作
		groupUserInfo.Status = 2
		fmt.Println(groupUserInfo)
		err := tx.Model(&model.DivisionRecord{}).Where("id = ?", groupUserInfo.Id).Updates(&groupUserInfo).Error
		// 检查是否有错误发生
		if err != nil {
			// 如果有错误，回滚事务
			tx.Rollback()
			return err
		} else {
			tx.Commit()
			return nil
		}
	} else {
		// 执行创建积分变动记录的操作
		groupUserInfo.Status = 6
		err := tx.Model(&model.DivisionRecord{}).Where("id = ?", groupUserInfo.Id).Updates(&groupUserInfo).Error
		if err != nil {
			// 如果有错误，回滚事务
			tx.Rollback()
			return err
		} else {
			tx.Commit()
			return nil
		}
	}
}

// 设置抽水比列
func (r *robotUser) UpDataPuPm(PuPm float64, GroupUser int) (error, float64) {
	// 开启一个新的事务
	tx := global.GVL_DB.Begin()
	User := &model.WeChatGroup{}
	err := tx.Model(&model.WeChatGroup{}).Where("id = ?", GroupUser).Find(&User).Error
	User.Pump = PuPm / 100
	err = tx.Model(&model.WeChatGroup{}).Where("id = ?", GroupUser).Updates(&User).Error
	if err != nil {
		tx.Rollback()
		return err, -1
	} else {
		tx.Commit()
		return nil, User.Pump
	}
}

// 获取抽水值
func (r *robotUser) GetPuPm(groupNumber int) (error, float64) {
	weChatGroup := &model.WeChatGroup{}
	err := global.GVL_DB.Model(&model.WeChatGroup{}).Where("id = ?", groupNumber).Find(weChatGroup).Error
	if err != nil {
		return err, 0
	}
	return nil, weChatGroup.Pump
}

// 清空机器人用户的流水抽水和上下分
func (*robotUser) ClearRobotUserTodayWater() {
	global.GVL_DB.Model(&model.WeChatGroupUser{}).Updates(map[string]interface{}{
		"run_water": 0, "returned_water": 0, "upward_division": 0, "lower_division": 0,
	})
}
